require("../less/riding.less");
document.ready(function() {
    //头部
    window.$utils.exerHeader('riding');
    //尾部
    window.$utils.footerFn('exercise');

    axios.defaults.baseURL = "http://139.9.177.51:8099";

    //获取累计骑行距离
    axios.get("/sports/exerciseData?id=" + localStorage.userId)
        .then(function(res) {
            document.querySelector('#runkm').textContent = res.data.data.ridekm.toFixed(2);
        })
        .catch(function(err) {
            console.log(err);
        })


    //点击go开始跑步
    //倒计时器
    document.querySelector('#runGo').addEventListener('click', function() {
        document.querySelector('.countdown-mask').style.display = 'block';
        let num = 3;
        let timeId1 = setInterval(function() {
            num--;
            if (num == 0) {
                document.querySelector('.countdown-text').textContent = "GO";
            } else if (num == -1) {
                document.querySelector('.countdown-mask').style.display = 'none';
                document.querySelector('.outdoor-run').style.display = 'block';
                clearInterval(timeId1);
                timer();
            } else {
                document.querySelector('.countdown-text').textContent = num;
            }
        }, 1000)
    })

    //记录跑步时间
    //计时器
    let timeId2 = null;
    let times = 0;

    function timer() {
        timeId2 = setInterval(function() {
            times++;
            let hours = parseInt(times / 60 / 60); //小时
            let minutes = parseInt(times / 60 % 60); //分
            let seconds = parseInt(times % 60); //秒
            hours = window.$utils.fillZero(hours);
            minutes = window.$utils.fillZero(minutes);
            seconds = window.$utils.fillZero(seconds);
            let timeStr = [hours, minutes, seconds].join(':');
            document.querySelectorAll('.runningTimer').forEach(function(v) {
                v.textContent = timeStr;
            })
            document.querySelector('#currentTime').textContent = window.$utils.getFMD('/');
            //绘制跑步时的地图
            runPositionMap();
        }, 1000)
    }

    //暂停按钮
    document.querySelector('#pauseBtn').addEventListener('click', function() {
        this.style.display = 'none';
        document.querySelector('#contiBtn').style.display = 'block';
        document.querySelector('#overBtn').style.display = 'block';
        clearInterval(timeId2);
        runPositionMap();

    })

    //继续按钮
    document.querySelector('#contiBtn').addEventListener('click', function() {
        document.querySelector('#contiBtn').style.display = 'none';
        document.querySelector('#overBtn').style.display = 'none';
        document.querySelector('#pauseBtn').style.display = 'block';
        timer();
    })

    //结束按钮
    document.querySelector('#overBtn').addEventListener('click', function() {
        this.style.display = 'none';
        document.querySelector('#contiBtn').style.display = 'none';
        document.querySelector('#pauseBtn').style.display = 'block';
        document.querySelector('.map-modal').style.display = 'block';
        document.querySelector('.outdoor-run').style.display = 'none';
        document.querySelector('#finishBtn').style.display = 'block';
        document.querySelector('.finish-data').style.display = 'flex';
        // 可以解决地图还没加载完的情况
        runPositionMap();
    })

    //完成按钮
    document.querySelector('#finishBtn').addEventListener('click', function() {
        //上传跑步数据
        let params = {
            id: parseInt(localStorage.userId),
            type: 2,
            takeTime: times,
            miles: distanceNum,
            averagerate: (distanceNum / times).toFixed(2),
            calorie: calorieNum,
        }

        axios.post("/sports/save", params)
            .then(function(res) {
                console.log(res);
                if (res.data.status == 0) {
                    window.$utils.tipsFn('保存数据成功', res.data.status);
                } else {
                    window.$utils.tipsFn('保存数据失败', res.data.status);
                }

            })
            .catch(function(err) {
                console.log(err);
            })

        setTimeout(function() {
            // 页面数据归零
            //直接刷新页面
            history.go(0);

        }, 1000)




    })

    //地图按钮
    document.querySelector('#mapBtn').addEventListener('click', function() {
        document.querySelector('.map-modal').style.display = 'block';
        document.querySelector('.outdoor-run').style.display = 'none';
        document.querySelector('#finishBtn').style.display = 'none';
        document.querySelector('.finish-data').style.display = 'none';
        // 可以解决地图还没加载完的情况
        runPositionMap();

    })

    //返回按纽
    document.querySelector('#returnBtn').addEventListener('click', function() {
        document.querySelector('.map-modal').style.display = 'none';
        document.querySelector('.outdoor-run').style.display = 'block';
    })

    //渲染当前时间
    document.querySelector('#currentTime').textContent = window.$utils.getFMD('/');

    //锁屏按钮和解锁按钮
    document.querySelector('#lockScreen').addEventListener('click', function() {
        document.querySelector('.clock-mask').style.display = 'block';
    })
    document.querySelector('#unlock').addEventListener('click', function() {
        document.querySelector('.clock-mask').style.display = 'none';
    })


    // 地图模态框的定位
    //随着跑步，地图位置发生改变

    var map = new BMap.Map("positionMap");
    let n = 0.0001; //定义全局变量，模仿跑步

    let positionArr = []; //将每秒的经度，纬度收集起来
    let distanceNum = 0;
    let speedNum = 0;
    let calorieNum = 0;


    function runPositionMap() {

        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                // let lng = r.longitude * 1; //经度
                // let lat = r.latitude * 1; //纬度

                //模仿骑行
                let lng = r.longitude * 1 + n; //经度
                let lat = r.latitude * 1 + n; //纬度
                n += 0.0002;



                var point = new BMap.Point(lng, lat);
                map.centerAndZoom(point, 16);


                positionArr.push({ lng: lng, lat: lat });
                if (positionArr.length >= 2) {
                    let x = positionArr[positionArr.length - 2]; //前一个点
                    let y = positionArr[positionArr.length - 1]; //前一个点

                    //绘制路线
                    drawRunRote(x, y);

                    // 计算距离
                    distanceNum += calcDistance(x, y) * 1; //转为数字型
                    document.querySelectorAll('.distanceRun').forEach(function(v) {
                        v.textContent = distanceNum.toFixed(2);
                    })

                    //计算配速
                    speedNum = calcPace(distanceNum, times);
                    document.querySelectorAll('.speedRun').forEach(function(v) {
                        v.textContent = speedNum;
                    })

                    //计算卡路里
                    calorieNum = calCalorie(distanceNum) * 1; //转为数字型
                    document.querySelectorAll('.calorieRun').forEach(function(v) {
                        v.textContent = calorieNum;
                    })
                }
            } else {
                alert('failed' + this.getStatus());
            }
        });
    }


    //初始化地图
    initMap();

    function initMap() {

        //绘制地图
        var map = new BMap.Map("runMap");
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                console.log(r)
                let lng = r.longitude * 1; //经度 //字符串强制转为数字
                let lat = r.latitude * 1; //纬度
                var point = new BMap.Point(lng, lat); //经度和纬度动态化
                map.centerAndZoom(point, 12);
            } else {
                alert('failed' + this.getStatus());
            }
        });
    }

    //绘制骑行路线
    function drawRunRote(x, y) {
        var polyline = new BMap.Polyline([
            new BMap.Point(x.lng, x.lat),
            new BMap.Point(y.lng, y.lat)
        ], { strokeColor: "red", strokeWeight: 10, strokeOpacity: 0 });
        map.addOverlay(polyline);
    }





    /* 
  根据经纬度计算距离
    startPoint:  起点 
    curPoint:  终点
*/
    function calcDistance(startPoint, curPoint) {
        let lat1 = startPoint.lat;
        let lng1 = startPoint.lng;

        let lat2 = curPoint.lat;
        let lng2 = curPoint.lng;

        var radLat1 = lat1 * Math.PI / 180.0;
        var radLat2 = lat2 * Math.PI / 180.0;
        var a = radLat1 - radLat2;
        var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;
        s = Math.round(s * 10000) / 10000;
        return s.toFixed(2) // 单位千米
    }

    /* 计算配速函数 
      d： 距离
      s： 时间
    */
    function calcPace(d, s) {
        let distance = d
        let spendTime = s / 60
        if (distance > 0 && spendTime > 0) {
            let pace = parseFloat(spendTime / distance)
            let m = Math.floor(pace)
            let s = ((pace - m) * 60).toFixed(0)
            return `${window.$utils.fillZero(m)}'${window.$utils.fillZero(s)}"`

        }
        return "--"
    }

    /* 计算卡路里 */
    function calCalorie(miles) {
        if (miles > 0) {
            let calorie = 60 * miles * 1.036;
            return calorie.toFixed(2)
        }
        return "--"
    }


})